#include "system/profile.h"

#include "system/logger.h"
#include "system/timer.h"

namespace dw {
	namespace system {

inline Profiler::Profiler()
:	_isEnabled(false)
{
	_header = "dotWare profiler";
}

inline void Profiler::Enable()
{
	_isEnabled = true;
	dwLogInform(_header.c_str());
	_timer.reset();
}

inline void Profiler::Disable()
{
	_isEnabled = false;
}

inline void Profiler::Toggle()
{
	_isEnabled ? Disable() : Enable();
}

inline void Profiler::BeginProfile(const std::string& name)
{
	ProfileIterator i = _profiles.find(name);

	if (i == _profiles.end())
		_profiles.insert(std::make_pair(name, new Profile(name)));
	i = _profiles.find(name);
	i->second->_startTime = _timer.getMilliSeconds();
	i->second->_numCall++;
}

inline void Profiler::EndProfile(const std::string& name)
{
	ProfileIterator i = _profiles.find(name);
	Profile& profile = *(i->second);

	profile._currentTime = _timer.getMilliSeconds() - profile._startTime;
	if (profile._currentTime > profile._maxTime) 
		profile._maxTime = profile._currentTime;
	if (profile._currentTime < profile._minTime) 
		profile._minTime = profile._currentTime;
	profile._totalTime += profile._currentTime;
}

template< typename T >
inline std::string ToString(const T& value)
{
	std::ostringstream oss;
	
	oss << std::right << std::fixed << std::setprecision(2) << value;
	return oss.str();
}

	} // namespace system
} // namespace dw
